package com.demo.task.ext

import android.util.Log
import com.demo.task.bean.PlanBean
import com.google.gson.Gson
import com.orhanobut.logger.Logger
import java.io.File

private const val TAG = "FileExt"
private val gson by lazy { Gson() }

fun String?.getUrlFileName(): String {
    return this?.substringBefore("?")?.ifEmpty { this }?.substringAfterLast("/").orEmpty()
}

fun List<String>.delRes() {
    val file = File(getResPath())
    if (file.exists()) {
        val localFiles = file.listFiles()?.map { it.name } ?: emptyList()
        val remoteFiles = this.map { it.getUrlFileName() }
        localFiles.filterNot { it in remoteFiles }.forEach {
            Log.i(TAG, "delRes: $it")
            Logger.i("delRes: $it")
            File(file, it).delete()
        }
    }
}

fun delCacheJson() {
    val file = File(getExternalFilesDir(), "cache.json")
    if (file.exists()) {
        file.delete()
    }
}

 fun readCache(): PlanBean? {
    return runCatching {
        val file = File(getExternalFilesDir(), "cache.json")
        val cacheContent = file.readText()
        gson.fromJson(cacheContent, PlanBean::class.java)
    }.onFailure {
        Log.e(TAG, "readCache: ", it)
    }.getOrNull()
}
